define(['app', 'js/directive/listTree', 'js/filter/tree2Arr', 'datetime', 'pagination', 'autocomplete', 'filesaver','floatlayer'], function(app) {
    'use strict';
    /*撞单审核管理*/
    app.controller('Conflict', function($scope, dataFactoryCRM, $q, $compile,$timeout) {
        $scope.conflictSource = '';
        $scope.customerInfo = '';
        $scope.ifdisplay = false;
        $scope.expression = false;
        $scope.IsRefund = true;
        $scope.express_A_show = false;
        $scope.express_B_show = false;
        $scope.param = {};
        // $scope.extradiv = false;
        // $scope.testdirective = true;
        // $scope.judgeobj = '';
        $scope.conflictpages = {
            pageAll: 1,
            pageNow: 1,
            pageSize: $scope.psize,
            k: 3
        };
        $scope.dealstatusdata = [{
                k: '0',
                v: '全部'
            },
            {
                k: '1',
                v: '成功'
            },
            {
                k: '2',
                v: '平分'
            },
            {
                k: '3',
                v: '失败'
            },
            {
                k: '4',
                v: '退款'
            }
        ]
        $scope.conflictstatus = [ //归属权不变
            // {k:'0',v:'未处理'},
            {
                k: '1',
                v: '成功'
            },
            {
                k: '2',
                v: '平分'
            },
            {
                k: '3',
                v: '失败'
            }, //小单用户，可以归属权不变，但是申诉失败
            {
                k: '4',
                v: '退款'
            }
        ]

        $scope.conflictDatalist = function() {
            $scope.$emit("BUSY");
            var url = "Conflict/index";
            // if (!$scope.param) {
            //     url += '?' + "psize=" + $scope.conflictpages.pageSize + "&p=" + $scope.conflictpages.pageNow;
            // } else {
            url += '?' + $.param($scope.param) + "&psize=" + $scope.conflictpages.pageSize + "&p=" + $scope.conflictpages.pageNow;
            // }
            dataFactoryCRM.getDataByAPI(url).then(function(_d) {
                // console.log(_d);
                if (_d.rcode == 1) {
                    $scope.conflictpages.pageSize = _d.psize;
                    $scope.conflictpages.pageAll = _d.pall;
                    $scope.conflictpages.pageNow = _d.p;
                    $scope.conflictSource = _d.data;
                } else {
                    $scope.conflictSource = '';
                    $scope.conflictpages.pageAll = 0;
                }
                $scope.$emit("NOTBUSY");
            });
        }
         //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function() {
            $scope.conflictDatalist();
        });

        //add conflict record radio button 	
        $scope.radioEvent = function(key) {
            $scope.radiobtn = key;
            // $scope.radiobtnEdit = key;
            if (key) {
                $scope.ifdisplay = true;
            } else {
                $scope.ifdisplay = false;
                $scope.dropdownUser = '';
            }
        }
        $scope.radioEvent(0);

        // add conflict record
        $scope.addConflict = function() {
            
            $scope.ifdisplay = false;
            $scope.dropdownstauts = 0;
            $scope.customerInfo = '';
            $scope.getCustomerServicePeople = '';
           
            $timeout(function() {
                $('#conflictId').form('clear');
                $scope.$broadcast('angucomplete-alt:clearInput');
                $('#extradiv').removeClass('ui basic red pointing prompt label transition visible');
                document.getElementById("extradiv").innerHTML = '';
            });
            
            $('.ui.add.modal').modal({
                observeChanges: true,
                onApprove: function() {
                    var strdelid = $("input:checkbox[name='u_pay_record']:checked").map(function() {
                        return this.id;
                    }).get().join(',');
                    $scope.arr_list = strdelid.split(',');
                    var strdelValue = $("input:checkbox[name='u_pay_record']:checked").map(function() {
                        return this.value;
                    }).get().join(',');
                    if (!strdelid && $scope.customerInfo) {
                        $('#extradiv').addClass('ui basic red pointing prompt label transition visible');
                        document.getElementById("extradiv").innerHTML = '请勾选撞单记录';
                        return false;
                    } else {
                        $scope.payamount = strdelValue.split(',');
                        $scope.UserId = $('#add_user').val();
                        if ($scope.dropdownUser == undefined) $scope.dropdownUser = '';
                        var formate = "customer_id=" + $scope.CustomerId + "&user_id=" + $scope.UserId + "&checkboxMsg=" + $scope.arr_list + '&payamount=' + $scope.payamount;
                        formate += "&radioMsg=" + $scope.radiobtn + "&dropdownMsg=" + $scope.dropdownstauts + "&textarea=" + $scope.textarea + "&note=" + $scope.note + '&dropdownUser=' + $scope.dropdownUser;
                        if ($('#conflictId').form('is valid')) {
                            function addSuccess() {
                                setTimeout(function() {
                                    $('.modal1').modal('show');
                                    //3s后关闭
                                    setTimeout(function() {
                                        $('.modal1').modal('hide')
                                    }, 3000)
                                }, 1000);
                            }
                            /**添加失败 */
                            function addFail() {
                                //添加失败了,
                                setTimeout(function() {
                                    $('.modal2').modal('show');
                                    //3s后关闭
                                    setTimeout(function() {
                                        $('.modal2').modal('hide')
                                    }, 3000)
                                }, 1000);
                            }
                            // $scope.$emit("BUSY");
                            dataFactoryCRM.postDataByAPI('Conflict/add', formate).then(function(_d) {
                                // console.log(_d);
                                if (_d.rcode == 1) {
                                    addSuccess();
                                    $scope.conflictDatalist();
                                    return true;
                                } else {
                                    addFail();
                                    $scope.$emit("NOTBUSY");
                                    $scope.msgAttention();
                                    return false;
                                }
                            });
                        } else {
                            return false;
                        }
                    }

                }
            }).modal('show');
            $scope.$watch('dropdownstauts', function() {
                if ($scope.dropdownstauts == 4) {
                    $scope.IsRefund = false;
                    $scope.ifdisplay = false;
                    $scope.radiobtn = 1;
                } else {
                    $scope.IsRefund = true;
                    $scope.radiobtn = 0;
                }
            }, true);
            
            $scope.UserMsg = [{}];
            $scope.CustomerMsg = [{}];
        }

        // 
        $scope.validcheckbox = function() {
            var strdelid = $("input:checkbox[name='u_pay_record']:checked").map(function() {
                return this.id;
            }).get().join(',');
            $scope.arr_list = strdelid.split(',');
            if (strdelid.length > 1) {
                $('#extradiv').removeClass('ui basic red pointing prompt label transition visible');
                document.getElementById("extradiv").innerHTML = '';
            }
        }

        //edit conflict record
        $scope.conflictEdit = function() {
            var param = this.con;
            $scope.disableInput = true;
            $scope.express_A_show = false;
            $scope.express_B_show = false;
            // get message from database
            $scope.busy = dataFactoryCRM.getDataByAPI('conflict/editConflictMsg?conflict_id=' + param.conflict_id + '&customer_id=' + param.customer_id)
                .then(function(d) {
                    // console.log(d);
                    if (d.rcode == 1) {
                        $scope.customerInfoEdit = d.data;
                        $scope.partthree = d.data_partthree;
                        for (var i = 0; i < 1; i++) {
                            $scope.textareaEdit = $scope.customerInfoEdit[i].notify;
                            $scope.noteEdit = $scope.customerInfoEdit[i].remark;
                            $scope.dropdownstautsEdit = $scope.customerInfoEdit[i].status;
                            $('#ConMsgEdit_value').val($scope.customerInfoEdit[i].customer_name);
                            $('#ConMsgUserEdit_value').val($scope.customerInfoEdit[i].username);
                            if ($scope.customerInfoEdit[i].customer_belong == 1) {
                                $scope.express_A = true;
                                $scope.express_A_show = true;
                                $scope.editdisplay = true;
                            } else {
                                $scope.express_A = false;
                                $scope.express_B_show = true;
                                $scope.editdisplay = false;
                            }
                        }
                        $scope.dropdownUserEdit = d.data_partfour;
                        if (d.data_partfour) $scope.labelshow = true;
                        else $scope.labelshow = false;
                    } else {
                        alert(d.msg);
                        return false;
                    }
                });

            $('.ui.edit.modal').modal({
                observeChanges: true,
                onApprove: function() {
                    return true;
                }
            }).modal('show');
        }

        //delete conflict records
        $scope.conflicDelte = function() {
                $scope.$emit("BUSY");
                var delparam = this.con;
                $('#conflict_del .content p').html("记录【客户姓名:" + delparam.nickname + "】确认删除吗？");
                // console.log(123);
                $('.modal3').modal({
                    onApprove: function() {
                        // dataFactoryCRM.postDataByAPI('conflict/conflictdel','conflict_id=' + delparam.conflict_id ).then(function(d){
                        dataFactoryCRM.postDataByAPI('conflict/conflictdel', {
                            conflict_id: delparam.conflict_id
                        }).then(function(d) {
                            if (d.code) {
                                if ($scope.conflictSource) {
                                    var i = 0;
                                    for (; i < $scope.conflictSource.length; i++) {
                                        if ($scope.conflictSource[i].conflict_id == delparam.conflict_id) {
                                            $scope.conflictSource.splice(i, 1);
                                            break;
                                        }
                                    }
                                }
                                return true;
                            } else {
                                $scope.$emit("NOTBUSY");
                                $scope.msgAttention();
                                return false;
                            }
                        });
                    }
                }).modal('show');
                $scope.$emit("NOTBUSY");
            }
            // $scope.testdirective = {name:'hhhhh'};
            //add customer message autocomplete 
        $scope.selectCustomer = function(selected) {
                if (selected) {
                    // $scope.testdirective = true; 
                    var CustomerId = selected.originalObject.customer_id;
                    if (selected.originalObject.customer_id) {
                        $scope.recordcustomerId = selected.originalObject.customer_id;
                    }
                    $('#add_customer').val(CustomerId);
                    $scope.CustomerId = CustomerId;
                    // ****************************
                    $scope.registerHiddenBlur = function(hiddenID, visibleID) {
                        $('#' + visibleID).blur(function() {
                            //延时触发blur，目的是让hidden input先于blur被赋值
                            setTimeout(function() {
                                $('#' + hiddenID).trigger('blur');
                            }, 100);
                        });
                    }
                    setTimeout(function() {
                        registerHiddenBlur('add_customer', 'ConMsg_value');
                    }, 500);
                    // *****************************
                    //get pay_record message of customer 	
                    dataFactoryCRM.postDataByAPI('Conflict/CustomerPayRecords', 'CustomerId=' + CustomerId)
                        .then(function(d) {
                            if (d.rcode) {
                                $scope.customerInfo = d.data;
                                $scope.judgeobj = 1;
                            } else {
                                $scope.customerInfo = {};
                            }
                        });
                    // get the person of servicing customer
                    dataFactoryCRM.postDataByAPI('Conflict/customerbelong', 'customer_id=' + CustomerId)
                        .then(function(d) {
                            if (d.rcode) {
                                $scope.customer_belong = d.data;
                            } else {
                                $scope.customer_belong = '';
                            }
                        });

                }
            }
            //User message autocomplete 
        $scope.selectUser = function(selected) {
            if (selected) {
                var UserId = selected.originalObject.user_id;
                if (selected.originalObject.user_id) {
                    $scope.recorduserId = selected.originalObject.user_id;
                }
                $('#add_user').val(UserId);
                $scope.GetUserID = UserId;
                $scope.UserId = UserId;
                // $scope.GetUserID = $scope.recorduserId; 
                $scope.change();
                // ****************************
                $scope.registerHiddenBlur = function(hiddenID, visibleID) {
                    $('#' + visibleID).blur(function() {
                        //延时触发blur，目的是让hidden input先于blur被赋值
                        setTimeout(function() {
                            $('#' + hiddenID).trigger('blur');
                        }, 100);
                    });
                }
                setTimeout(function() {
                    $scope.registerHiddenBlur('add_user', 'ConMsgUser_value');
                }, 500);

                // *****************************				
            }
        }

        //UserManager message autocomplete 
        $scope.selectUserManager = function(selected) {
            if (selected) {
                var UserManagerId = selected.originalObject.user_id;
                if (selected.originalObject.user_id) {
                    $scope.recorduserManagerId = selected.originalObject.user_id;
                }
                $('#search_userManager').val(UserManagerId);
                $scope.usermanagerId = UserManagerId;
                $scope.param.search_userManager = $('#search_userManager').val();
            }
        }

        // get customerServicePeople
        $scope.change = function() {
            var strdelid = $("input:checkbox[name='u_pay_record']:checked").map(function() {
                return this.id;
            }).get().join(',');
            $scope.arr_list = strdelid.split(',');
            if ($scope.CustomerId && $scope.arr_list[0] != '') {
                // dataFactoryCRM.postDataByAPI('Conflict/getCustomerServicePeople','customerMsg=' + $scope.arr_list + '&UserID=' + $scope.GetUserID)
                dataFactoryCRM.postDataByAPI('Conflict/getCustomerServicePeople', {
                        customerMsg: $scope.arr_list,
                        UserID: $scope.GetUserID
                    })
                    .then(function(d) {
                        $scope.getCustomerServicePeople = d;
                    });
            } else {
                $scope.getCustomerServicePeople = '';
                $('#cleardropdown').dropdown('clear');
            }
        }

        // customer angucomplete
        $scope.inputChanged = function($item) {
             //WJW 20170725 修改
            $scope.detect = $item;
        }
        $scope.$watch('detect', function(newvalue, oldvalue) {
            dataFactoryCRM.getDataByAPI('Conflict/getcustomername?parame=' + newvalue )
                .then(function(d) {
                    if(d.rcode == 1){
                        $scope.CustomerMsg = d.CustomerMsg;
                    }else{
                        $scope.CustomerMsg = [{}];
                    }
                });
        }); 
        // user angucomplete
        $scope.UserinputChanged = function($item) {
            //WJW 20170725 修改
            $scope.detectUser = $item;
        }
        $scope.$watch('detectUser', function(newvalue, oldvalue) {
            if(newvalue!='') {
                dataFactoryCRM.getDataByAPI('Conflict/getusername?parame=' + newvalue )
                    .then(function(d) {
                        if(d.rcode == 1){
                            $scope.UserMsg = d.getUser;
                        }else{
                            $scope.UserMsg = [{}];
                        }
                    });
            }
        }); 
        $scope.UserManagerinputChanged = function($item) {
                $scope.detectUserManager = $item;
                $scope.$watch('recorduserManagerId', function(newvalue, oldvalue) {
                    if (newvalue != oldvalue) {
                        dataFactoryCRM.postDataByAPI('Conflict/getusermanagername', 'userManagerId=' + $scope.recorduserManagerId)
                            .then(function(d) {
                                $scope.usermanagernamerecord = d.nickname;
                            });
                    }
                });
                $scope.$watch('detectUserManager', function() {
                    if ($scope.usermanagerId && $scope.detectUserManager != $scope.usermanagernamerecord && $scope.detectUserManager != '') {
                        $('#search_userManager').val('');
                        $scope.param.search_userManager = -1;
                    } else if ($scope.usermanagerId && $scope.detectUserManager == $scope.usermanagernamerecord) {
                        $('#search_userManager').val($scope.recorduserManagerId);
                        $scope.param.search_userManager = $('#search_userManager').val();
                    } else if (!$scope.usermanagerId && $scope.detectUserManager != '') {
                        $scope.param.search_userManager = -1;
                    } else if ($scope.usermanagerId && $scope.detectUserManager == '') {
                        $scope.param.search_userManager = '';
                    } else if (!$scope.usermanagerId && $scope.detectUserManager == '') {
                        $scope.param.search_userManager = '';
                    }
                });
            }
            // export records
            // $scope.exportRecords = function(){
            // 	if(!$scope.param){
            // 		var _url = 'Conflict/exportRecords';	
            // 	}else{
            // 		var _url = 'Conflict/exportRecords?' + $.param($scope.param);
            // 	}
            //     dataFactoryCRM.getDataByAPIS(_url).then(function(response) {
            //         var blob = new Blob([response], {
            //             type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            //         });
            //         saveAs(blob,  '撞单数据记录表' + '.xls');
            //     });
            // }

        // get user && customer message
        var urls = 'Conflict/GetMsg';
        dataFactoryCRM.getDataByAPI(urls).then(function(_d) {
            if (_d.rcode) {
                $scope.CustomerMsg = _d.data;
            }
            //   else
            //     alert(_d.msg);
        });
        var urls = 'Conflict/GetUserMsg';
        dataFactoryCRM.getDataByAPI(urls).then(function(_d) {
            if (_d.rcode) {
                $scope.UserMsg = _d.data;
            }
            //   else
            //     alert(_d.msg);
        });
        // get userManager message;
        var urls = 'Conflict/GetUserManagerMsg';
        dataFactoryCRM.getDataByAPI(urls).then(function(_d) {
            if (_d.rcode) {
                $scope.UserManagerMsg = _d.data;
            }
            //   else
            //     alert(_d.msg);
        });

    });
});